package com.wh1200.mybatis.xmlless.resolver

import cn.hutool.core.util.ReflectUtil
import com.wh1200.mybatis.xmlless.AnnotationSupport
import com.wh1200.mybatis.xmlless.config.MappingResolverProxy
import com.wh1200.mybatis.xmlless.model.ClassInfo
import com.wh1200.mybatis.xmlless.model.FieldMappingList
import com.wh1200.mybatis.xmlless.model.XmllessTableInfo
import com.wh1200.mybatis.xmlless.model.base.BaseClassWrapper
import java.lang.reflect.Field


/**
 *
 * Created by 吴昊 on 2018/12/10.
 *
 * @author 吴昊
 * @since 0.0.2
 */
object MappingResolver {

  private val instance: MappingResolverProxy = MappingResolverProxy()

  fun getAllMappings(): List<FieldMappingList> {
    return instance.getAllMappings()
  }

  fun clearCache() {
    instance.clearCache()
  }

  fun getMappingCache(modelClassName: String): FieldMappingList? {
    return instance.getMappingCache(modelClassName)
  }

  fun getMappingCache(tableInfo: XmllessTableInfo): FieldMappingList {
    val mapping = instance.getMappingCache(tableInfo.entityTypeName)
    return if (mapping == null) {
      instance.resolve(tableInfo, true)
    } else {
      mapping
    }
  }

  fun getMappingCache(modelClass: Class<*>): FieldMappingList? {
    return instance.getMappingCache(modelClass)
  }

  fun resolveNonEntityClass(
      wrapper: BaseClassWrapper,
      modelClassName: String,
      tableInfo: XmllessTableInfo,
      currentTableInfo: XmllessTableInfo
  ): FieldMappingList {
    return instance.resolveNonEntityClass(
        ClassInfo[wrapper], modelClassName,
        tableInfo, currentTableInfo
    )
  }

  fun resolve(
      tableInfo: XmllessTableInfo,
      useCache: Boolean = true
  ): FieldMappingList {
    return instance.resolve(tableInfo, useCache)
  }

  fun resolveFields(modelClass: Class<*>): List<Field> {
    return ReflectUtil.getFields(modelClass).filter {
      !AnnotationSupport.isTransient(it)
    }
  }

}
